package com.siemens.industrial.utils;

import com.siemens.industrial.model.JobType;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Map;

/**
 * Created by David on 2016/11/16.
 */
public class SocketClient {
    Socket socket = null;
    BufferedReader br = null;
    PrintWriter printWriter = null;

    public SocketClient() {
        socket = new Socket();
    }

    public boolean getSocketConnection() throws IOException {
        if (socket == null)
            return false;
        if(!socket.isConnected())
            socket.connect(new InetSocketAddress("127.0.0.1", 10001));

        System.out.println("Socket=" + socket);
        return true;
    }

    public SocketClient sendMessage(String msg) {
        try {
            printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                    socket.getOutputStream())));

            printWriter.println(msg);
            printWriter.flush();

        } catch (IOException e) {
            e.printStackTrace();
            close();
        }

        return this;
    }


    public void sendMessage(String msg,String data) {
        try {
            this.getSocketConnection();
            printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                    socket.getOutputStream())));

            printWriter.println(msg);
            printWriter.println(data);
            printWriter.flush();

        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            this.close();
        }
    }

    public String receiveMessage() throws IOException {
        br = new BufferedReader(new InputStreamReader(
                socket.getInputStream()));
        return br.readLine();
    }

    public void close() {
        try {
            if(br !=null)
                br.close();

            if(printWriter !=null)
                printWriter.close();

            if(socket !=null)
                socket.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    public boolean sendRequest(String type) {
        try {
            getSocketConnection();
            sendMessage(type);
            return true;
        } catch (IOException e) {
            System.out.println(e.getMessage());
            return false;
        } finally {
            this.close();
        }
    }
}
